<template>
  <div class="recruit">

    <div class="recruit-header">
      <div class="recruit-header-content">
        <div class="recruit-header-img">
        </div>
      </div>
    </div>


    <div class="recruit-container">

      <div class="enter">

        <div class="enter-hd">
          <div class="desc">
            全国范围内诚招合作伙伴。诚挚邀请有实力、有本地资源的伙伴加入，共赢本地生活美好未来！
            <button type="button" class="kw-btn btn-text btn-large">
              <span class="kw-btn__inner" @click="openDialogVisible">查看申请详情</span>

            </button>
          </div>
          <div>
            <h2>成为商家，只需三步</h2>
            <div class="steps">
              <div class="steps-icon"><img
                  src=""
                  alt="">
                申请
              </div>
              <div class="steps-arrow"><img
                  src=""
                  alt=""></div>
              <div class="steps-icon"><img
                  src="//shadow.elemecdn.com/faas/daili-recruit-gray/static/img/examine.19616be.png" alt="">
                审批
              </div>
              <div class="steps-arrow"><img
                  src=""
                  alt=""></div>
              <div class="steps-icon"><img
                  src=""
                  alt="">
                开店
              </div>
            </div>
          </div>
        </div>

        <!-- 注册列表 -->
        <div class="enter-register">
           

          <el-form :model="form"  ref="formRef"   label-width="140px">

            <div v-if="step===1">
              <el-form-item label="联系人手机号" prop="loginName" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' },{validator:mobileValidator,trigger: 'blur'}]">
                <el-input v-model="form.loginName"  ></el-input>

                <div class="mix-input-btn">
                  <!-- 发短信的按钮 -->
                  <el-link  :disabled="btnSendVisable" @click="sendSms">{{smsinfo}}</el-link>                
                </div>
              </el-form-item>

              <el-form-item label="验证码" prop="code" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.code"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :disabled="loginDisabled" @click="btnNext">立即注册</el-button>
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="agree">
                  我已阅读并同意
                  <a href="/#/safety-policy" target="_blank" class="el-link el-link--primary is-underline">华信商家版隐私政策</a>
                </el-checkbox>

              </el-form-item>

            </div>

            <div v-if="step===2">

              <el-form-item label="商家名称" prop="name" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.name" placeholder="商家名称" />
              </el-form-item>

              <el-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.phone" placeholder="联系电话" />
              </el-form-item>

              <el-form-item label="密码" prop="loginPwd" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input type="password" v-model="form.loginPwd" placeholder="密码" />
              </el-form-item>

              <el-form-item label="确认密码" prop="reLoginPwd" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input type="password" v-model="form.reLoginPwd" placeholder="确认密码" />
              </el-form-item>

              <el-form-item label="地图位置" prop="longitude" style="text-align:left;" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <span>经度:{{form.longitude}} 纬度:{{form.latitude}}</span>
                <el-button type="primary" @click="mapShow=true">选择位置</el-button>  

                <div style="display:none;">
                  <el-input v-model="form.longitude" />
                </div>
              </el-form-item>

              <el-form-item label="商家地址" prop="address" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.address" placeholder="商家地址" />
              </el-form-item>

              <el-form-item label="商家图片" prop="picture" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                
                
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl" 
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.picture" :src="form.picture" class="avatar" width="350" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>

                <div style="display:none;">
                  <el-input v-model="form.picture" />
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="btnSave">提交信息</el-button>
              </el-form-item>

            </div>

            <div v-if="step===3">
              <el-result icon="success" title="申请信息已发送" subTitle="请耐心等待审核结果,会以短信通您.">
              </el-result>
            </div>


          </el-form>

        </div>

      </div>

    </div>


    <!-- 申查申请 -->
    <el-dialog title="申请详情" v-model="dialogVisible" width="450px">
      <div class="apply-detail">
        <div class="apply-detail-item">
          <h2>
            合作商申请基本条件：
          </h2>
          <ul>
            <li>
              有正规业务经营的公司资质，盈利状况良好；
            </li>
            <li>
              熟悉当地城市餐饮行业发展状况，在当地拥有良好的口碑资源；
            </li>
            <li>
              在当地拥有较强的政府人脉关系及宣传推广资源；
            </li>
            <li>
              较强的运营能力及成熟的行业经验；
            </li>
            <li>
              具备较强的经济实力；
            </li>
          </ul>
        </div>
        <div class="apply-detail-item">
          <h2>
            报名须知：
          </h2>
          <ul>
            <li>
              请详细阅读合作商申请基本条件；
            </li>
            <li>
              请确保您填写的信息真实、有效，如在申请过程中存在虚假信息，该平台有权随时终止合作流程；
            </li>
            <li>
              填写过程需要您用心填写，时间约2分钟；
            </li>
            <li>
              如您已经阅读完成，请继续您的报名！
            </li>
          </ul>
        </div>
      </div>

    </el-dialog>

    <!--选择地图 -->
     <el-dialog title="选择位置" v-model="mapShow" width="800px"   >
        <div class="mapdialog"> 
           <baiduSearch :itemData="form" @myclick="localCallback"  style="height: 400px;"></baiduSearch>
        </div>
     </el-dialog>

  </div>
</template>

<script setup> 
  import { ref, watch} from 'vue'
  import {  Plus } from '@element-plus/icons-vue'
  import { ElMessage  } from 'element-plus'
  import store from '@/store/index.js'
  import {isPhone} from '@/utils/index.js'
  import {merchandiserPhoneApi,smsApi, smsValidatorApi} from '@/api/sms.js'
  import {registerApi} from '@/api/merchandiser.js'
  
  //引用自定义组件
  //import baiduDisplay from '@/components/BaiduAddress/display.vue'
  import baiduSearch from '@/components/BaiduAddress/index.vue'
  
  //定义国际化的语言的文件
  import {  useI18n } from 'vue-i18n';
  const {  t } = useI18n();
  
  const { proxy } = getCurrentInstance(); 
  
 
  // 百度地图对话框显示
  const mapShow = ref(false)
  // 当前步骤
  const step = ref(1)
  // 倒计时
  const countDownNum = ref(0)
  // 是否同意
  const agree = ref(false)
  //对话框
  const dialogVisible = ref(false)
  // 手机号是否使用过
  const isUsed = ref(false)
  const smsinfo = ref('发送验证码')
  // 发送短信按钮是否禁用(true禁用，false启用 )
  const btnSendVisable = ref(true)
 
   
   //记录全局的定时任务的ID
   let timeIntervalId;
  
  //图片上传地址
 
  const imageUploadUrl =ref(process.env.VUE_APP_BASE_API+'/front/upload/image')
   
   //自己的定义额外参数
   const data = reactive({
        form: {
             picture: undefined,
             address: undefined,
             latitude: undefined,
             longitude: undefined,
             status: '0',
             loginName: undefined
           } 
   });
   
   ///自己的定义额外参数,用来使用的
   const { form} = toRefs(data);
  
  const loginDisabled = computed(() => {
    //账户被使用
    if (isUsed.value) {
      return true;
    } 
    if (!agree.value) {
      return true;
    }
    // 如果不为空
    if (form.value.loginName) {
      // 再验证手机号码格式是否正确，如果正确
      if (isPhone(form.value.loginName)) {
        return false
      } else {
        // 格式不正确
        return true
      }
    }
    return true
  });
  
  
  // 提交数据
  function btnSave(){
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          registerApi(form.value).then(resp=> {
            //走到下一步
            step.value=3;
          })          
        }
    }); 
  }
  
  //发送短信验证码
  function sendSms(){ 
    
    smsApi(form.value.loginName).then(resp=> { 
      //禁用发送短信的按钮
      btnSendVisable.value= true
      //得到倒计时功能
      countDownNum.value= resp.data.seconds 
      smsinfo.value='('+countDownNum.value+')s重新发送'
      
      //倒计时线程
      timeIntervalId=setInterval(()=> {        
        countDownNum.value--;
        if(countDownNum.value<=0){
          smsinfo.value='发送验证码'
          //判断是否可以重新发送验证码
          btnSendVisable.value= false           
          //清除倒计时线程
          clearInterval(timeIntervalId);
        }else{
           smsinfo.value='('+countDownNum.value+')s重新发送'
        } 
      },1000);      
      
    })
  }
  
  //下一步
  function btnNext(){
    //验证有效性
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
          smsValidatorApi(form.value).then(resp=> {
            //走到下一步
            step.value=2;
          })          
        }
    });
    
  }
  
  //查看申请详情
  function openDialogVisible(){
    dialogVisible.value= true
  }
  
  //图片上传验证
  function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG) {
           ElMessage.error('上传头像图片只能是 JPG、PNG 格式!');
        }
        if (!isLt2M) {
           ElMessage.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
  }
  
  
  function handleAvatarSuccess(res, file) {
    if(res.code===200){
       form.value.picture= res.data.image_url
    }else{
       ElMessage.error( res.msg);
    } 
   } 
   
     // 如何vu3中的 观察手机号的变化，需要深度监听
     //immediate选项用于指定是否在开始监听时立即执行回调函数，默认为false；deep选项用于指定是否进行深度监听，默认为false
     //watch允许监听 reactive中的变量和 ref引用的变量的value
     // 提供一个 getter 函数
    watch( () => data.form.loginName, (newVal, oldVal) => {  
       if(newVal && isPhone(newVal)){
           btnSendVisable.value =false
         }else{
           btnSendVisable.value= true
         }
       } 
    )
    
    watch(() => isUsed.value,  (newVal, oldVal) => {             
        if(newVal){
            btnSendVisable.value =true
          }else{
            btnSendVisable.value= false
          }
     })
   
 
 //自定义表单验证 （实际情况来选项配置）
 function mobileValidator(rule, value, callback){
   const regex=/1[3,4,5,6,8,9]\d{9}/ 
   if (value === '') {
     callback(new Error('手机号不能为空'));
   } else if (!regex.test(value)) {
     callback(new Error('手机号码格式不正确，只支持(13|14|15|17|18|19)开头的!'));
   } else {
     // ajax远程调用，判断是否存在
     merchandiserPhoneApi(value).then(resp=> {      
        if(resp.data){
          isUsed.value=true
          callback(new Error(resp.data));
        }else{
          isUsed.value=false
          callback();
        }
     })
      
   }
 }
 
 
 //百度地图位置选择
 function localCallback(value){
   mapShow.value=false 
   form.value.latitude= value.latitude
   form.value.longitude=value.longitude
   form.value.address=value.address
 
 }
   
  
</script>

<style scoped>
  
  .mapdialog{ 
    clear: both;
    height:460px ;
  }
  
  .recruit-header {
    background: #009bff;
    background: -webkit-gradient(linear, left top, right top, from(#00adff), to(#0082ff));
    background: linear-gradient(90deg, #00adff, #0082ff);
  }

  .recruit-header-content {
    position: relative;
    width: 940px;
    margin: 0 auto;
    height: 200px;
  }

  .recruit-header-img {
    position: absolute;
    left: -250px;
    width: 1440px;
    height: 100%;
    background: url(https://img.alicdn.com/imgextra/i1/O1CN01B3IqWN1lKuFrQqyvs_!!6000000004801-2-tps-5760-800.png) 50% no-repeat;
    background-size: cover;
  }

  .recruit-container {
    width: 940px;
    margin: 0 auto;
  }


  .enter {
    padding: 16px 16px 0;
    background: #fff;
    max-width: 652px;
    margin: 0 auto;
  }

  .recruit-container>div {
    min-height: calc(100vh - 200px);
  }

  .enter-hd {
    text-align: center;
  }

  .desc {
    text-align: left;
    background: #f5f7fa;
    border-radius: 6px;
    font-size: 13px;
    line-height: 22px;
    color: #909399;
    padding: 15px;
    margin-bottom: 32px;
  }

  .kw-breadcrumb-item,
  .kw-btn,
  .kw-checkbox .kw-checkbox-appearance,
  .kw-link,
  .kw-modal,
  .kw-pager li,
  .kw-pagination-size,
  .kw-pagination-total,
  .kw-radio .kw-radio-appearance,
  .kw-tooltip {
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
  }

  .kw-btn {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    border: 1px solid transparent;
    cursor: pointer;
    outline: none;
    font-weight: 500;
    text-decoration: none;
    vertical-align: middle;
  }


  .kw-btn.btn-large {
    height: 40px;
    line-height: 38px;
    padding: 0 20px;
    border-radius: 4px;
    font-size: 14px;
  }

  .kw-btn.btn-text {
    color: #606266;
    background-color: transparent;
    padding: 0;
    border: none;
    position: relative;
    background: none;
  }

  .desc .kw-btn {
    color: #606266;
    height: 22px;
    line-height: 22px;
    vertical-align: baseline;
  }

  .enter-hd h2 {
    color: #303133;
    font-size: 18px;
    font-weight: 400;
  }

  .steps {
    padding: 30px 0 40px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: distribute;
    justify-content: space-around;
    font-size: 14px;
    color: #606266;
    border-bottom: 1px solid #e4e7ed;
  }

  .steps-icon {
    width: 64px;
  }


  .steps-icon img {
    width: 100%;
    margin-bottom: 10px;
  }

  .steps-arrow {
    padding-top: 14px;
  }

  .enter-register {
    padding: 25px 0;
    text-align: center;
  }

  .apply-detail-item {
    padding: 12px 0;
  }

  .apply-detail-item:first-child {
    border-bottom: 1px solid #e4e7ed;
  }

  .apply-detail h2 {
    font-size: 16px;
    color: #303133;
    line-height: 16px;
    font-weight: 400;
    margin-bottom: 10px;
  }

  .apply-detail ul {
    padding: 0;
    list-style: none;
  }

  .apply-detail-item ul li {
    font-size: 14px;
    color: #606266;
    padding-left: 20px;
    line-height: 24px;
    position: relative;
  }

  .apply-detail-item ul li:after {
    position: absolute;
    content: "";
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #c0c4cc;
    left: 0;
    top: 9px;
  }

  .apply-detail-item {
    padding: 12px 0;
  }

  .apply-detail h2 {
    font-size: 16px;
    color: #303133;
    line-height: 16px;
    font-weight: 400;
    margin-bottom: 10px;
  }

  .enter-register {
    padding: 25px 0;
    text-align: center;
  }

  .enter-register .mix-input-btn {
    background: #fff;
    font-size: 12px;
    position: absolute;
    right: 2px;
    top: 10px;
    color: #303133;
    font-weight: 500;
    height: 20px;
    line-height: 20px;
    padding: 0 15px;
    border-left: 1px solid #dcdfe6;
    cursor: pointer;
  }

  .enter-register .mix-input-btn .el-link:after {
    border-color: transparent;
  }
</style>
